import { format, formatDistanceToNow, parseISO } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import type { SubmissionStatus, ProgrammingLanguage } from '@/types'
import { Difficulty } from '@/types'

/**
 * 格式化日期时间
 */
export function formatDateTime(date: string | Date, pattern = 'yyyy-MM-dd HH:mm:ss'): string {
  const dateObj = typeof date === 'string' ? parseISO(date) : date
  return format(dateObj, pattern, { locale: zhCN })
}

/**
 * 格式化相对时间
 */
export function formatRelativeTime(date: string | Date): string {
  const dateObj = typeof date === 'string' ? parseISO(date) : date
  return formatDistanceToNow(dateObj, { 
    addSuffix: true,
    locale: zhCN 
  })
}

/**
 * 格式化文件大小
 */
export function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 Bytes'
  
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

/**
 * 格式化内存使用量
 */
export function formatMemory(kb: number): string {
  if (kb < 1024) return `${kb} KB`
  return `${(kb / 1024).toFixed(1)} MB`
}

/**
 * 格式化执行时间
 */
export function formatExecutionTime(ms: number): string {
  if (ms < 1000) return `${ms} ms`
  return `${(ms / 1000).toFixed(2)} s`
}

/**
 * 获取难度标签样式类
 */
export function getDifficultyClass(difficulty: Difficulty): string {
  const classes = {
    [Difficulty.EASY]: 'bg-green-100 text-green-800 border-green-200',
    [Difficulty.MEDIUM]: 'bg-yellow-100 text-yellow-800 border-yellow-200',
    [Difficulty.HARD]: 'bg-red-100 text-red-800 border-red-200'
  }
  return classes[difficulty] || classes[Difficulty.EASY]
}

/**
 * 获取难度标签文本
 */
export function getDifficultyText(difficulty: Difficulty): string {
  const texts = {
    [Difficulty.EASY]: '简单',
    [Difficulty.MEDIUM]: '中等',
    [Difficulty.HARD]: '困难'
  }
  return texts[difficulty] || '未知'
}

/**
 * 获取提交状态样式类
 */
export function getStatusClass(status: SubmissionStatus): string {
  const classes = {
    pending: 'bg-gray-100 text-gray-800',
    judging: 'bg-blue-100 text-blue-800',
    accepted: 'bg-green-100 text-green-800',
    wrong_answer: 'bg-red-100 text-red-800',
    time_limit_exceeded: 'bg-yellow-100 text-yellow-800',
    memory_limit_exceeded: 'bg-orange-100 text-orange-800',
    runtime_error: 'bg-purple-100 text-purple-800',
    compile_error: 'bg-pink-100 text-pink-800',
    system_error: 'bg-gray-100 text-gray-800'
  }
  return classes[status] || classes.system_error
}

/**
 * 获取编程语言显示名称
 */
export function getLanguageDisplayName(language: ProgrammingLanguage): string {
  const names = {
    cpp: 'C++',
    java: 'Java',
    python: 'Python 2',
    python3: 'Python 3',
    javascript: 'JavaScript',
    go: 'Go',
    rust: 'Rust',
    c: 'C'
  }
  return names[language] || language
}

/**
 * 获取Monaco Editor语言ID
 */
export function getMonacoLanguage(language: ProgrammingLanguage): string {
  const mapping = {
    cpp: 'cpp',
    java: 'java',
    python: 'python',
    python3: 'python',
    javascript: 'javascript',
    go: 'go',
    rust: 'rust',
    c: 'c'
  }
  return mapping[language] || 'plaintext'
}

/**
 * 防抖函数
 */
export function debounce<T extends (...args: any[]) => any>(
  func: T,
  wait: number,
  immediate = false
): (...args: Parameters<T>) => void {
  let timeout: number | null = null
  
  return function executedFunction(...args: Parameters<T>) {
    const later = () => {
      timeout = null
      if (!immediate) func(...args)
    }
    
    const callNow = immediate && !timeout
    
    if (timeout) clearTimeout(timeout)
    timeout = setTimeout(later, wait)
    
    if (callNow) func(...args)
  }
}

/**
 * 节流函数
 */
export function throttle<T extends (...args: any[]) => any>(
  func: T,
  limit: number
): (...args: Parameters<T>) => void {
  let inThrottle: boolean
  
  return function executedFunction(...args: Parameters<T>) {
    if (!inThrottle) {
      func(...args)
      inThrottle = true
      setTimeout(() => (inThrottle = false), limit)
    }
  }
}

/**
 * 深拷贝
 */
export function deepClone<T>(obj: T): T {
  if (obj === null || typeof obj !== 'object') return obj
  if (obj instanceof Date) return new Date(obj.getTime()) as T
  if (obj instanceof Array) return obj.map(item => deepClone(item)) as T
  if (typeof obj === 'object') {
    const clonedObj = {} as T
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key])
      }
    }
    return clonedObj
  }
  return obj
}

/**
 * 生成随机字符串
 */
export function generateId(length = 8): string {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

/**
 * 验证邮箱格式
 */
export function validateEmail(email: string): boolean {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(email)
}

/**
 * 验证用户名格式
 */
export function validateUsername(username: string): boolean {
  const usernameRegex = /^[a-zA-Z0-9_-]{3,20}$/
  return usernameRegex.test(username)
}

/**
 * 验证密码强度
 */
export function validatePassword(password: string): {
  valid: boolean
  message: string
  strength: 'weak' | 'medium' | 'strong'
} {
  if (password.length < 6) {
    return {
      valid: false,
      message: '密码至少需要6个字符',
      strength: 'weak'
    }
  }
  
  let strength: 'weak' | 'medium' | 'strong' = 'weak'
  let score = 0
  
  // 长度
  if (password.length >= 8) score += 1
  if (password.length >= 12) score += 1
  
  // 复杂性
  if (/[a-z]/.test(password)) score += 1
  if (/[A-Z]/.test(password)) score += 1
  if (/[0-9]/.test(password)) score += 1
  if (/[^A-Za-z0-9]/.test(password)) score += 1
  
  if (score >= 4) strength = 'strong'
  else if (score >= 2) strength = 'medium'
  
  return {
    valid: true,
    message: strength === 'weak' ? '密码强度较弱，建议使用大小写字母、数字和特殊字符' : '密码强度良好',
    strength
  }
}

/**
 * 格式化数字
 */
export function formatNumber(num: number): string {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'M'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K'
  }
  return num.toString()
}

/**
 * 计算百分比
 */
export function calculatePercentage(value: number, total: number): number {
  if (total === 0) return 0
  return Math.round((value / total) * 100)
}

/**
 * 获取用户头像URL
 */
export function getAvatarUrl(userId: number, avatarUrl?: string): string {
  if (avatarUrl && avatarUrl !== '/static/avatars/default.jpg') {
    const filename = avatarUrl.split('/')[3]
    console.log(filename);
    
    return avatarUrl.startsWith('http') ? avatarUrl : `${import.meta.env.VITE_API_BASE_URL}${"/v1/avatar/file/"+filename}`
  }

  // 使用API获取头像
  return `${import.meta.env.VITE_API_BASE_URL}/v1/avatar/${userId}`
}

/**
 * 复制文本到剪贴板
 */
export async function copyToClipboard(text: string): Promise<boolean> {
  try {
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text)
      return true
    } else {
      // 降级方案
      const textArea = document.createElement('textarea')
      textArea.value = text
      textArea.style.position = 'absolute'
      textArea.style.left = '-999999px'
      document.body.appendChild(textArea)
      textArea.select()
      document.execCommand('copy')
      document.body.removeChild(textArea)
      return true
    }
  } catch (error) {
    console.error('Failed to copy text:', error)
    return false
  }
}

/**
 * 滚动到指定元素
 */
export function scrollToElement(element: HTMLElement | string, offset = 0): void {
  const target = typeof element === 'string' ? document.querySelector(element) : element
  if (target && target instanceof HTMLElement) {
    const top = target.offsetTop - offset
    window.scrollTo({ top, behavior: 'smooth' })
  }
}

/**
 * 获取URL参数
 */
export function getQueryParam(param: string): string | null {
  const urlParams = new URLSearchParams(window.location.search)
  return urlParams.get(param)
}

/**
 * 设置URL参数
 */
export function setQueryParam(param: string, value: string): void {
  const url = new URL(window.location.href)
  url.searchParams.set(param, value)
  window.history.replaceState({}, '', url.toString())
}

/**
 * 移除URL参数
 */
export function removeQueryParam(param: string): void {
  const url = new URL(window.location.href)
  url.searchParams.delete(param)
  window.history.replaceState({}, '', url.toString())
}

/**
 * 标签中英文对照表
 */
const tagsChinese = {
  "array": "数组",
  "string": "字符串",
  "linked-list": "链表",
  "tree": "树",
  "graph": "图",
  "dynamic-programming": "动态规划",
  "greedy": "贪心",
  "backtracking": "回溯",
  "binary-search": "二分查找",
  "sorting": "排序",
  "math": "数学",
  "bit-manipulation": "位运算",
  "heap": "堆",
  "trie": "字典树",
  "stack": "栈",
  "queue": "队列",
  "hash-table": "哈希表",
  "depth-first-search": "深度优先搜索",
  "breadth-first-search": "广度优先搜索",
  "union-find": "并查集",
  "segment-tree": "线段树",
  "binary-indexed-tree": "树状数组",
  "topological-sort": "拓扑排序",
  "prefix-sum": "前缀和",
  "sliding-window": "滑动窗口",
  "two-pointers": "双指针",
  "monotonic-stack": "单调栈",
  "state-compression": "状态压缩",
  "ai": "人工智能",
  "recursion": "递归",
  "divide-and-conquer": "分治",
  "monotonic-queue": "单调队列",
  "dynamic-greedy": "动态贪心",
  "game-theory": "博弈论",
  "geometry": "几何",
  "string-matching": "字符串匹配",
  "design": "设计",
  "doubly-linked-list": "双向链表",
  "binary-tree": "二叉树",
  "acm": "ACM"
}

/**
 * 获取标签的中文名称
 */
export function getChineseTagName(tag: any): string {
  // 如果标签有display_name且是中文，直接返回
  if (tag.display_name && /[\u4e00-\u9fa5]/.test(tag.display_name)) {
    return tag.display_name
  }
  
  // 如果标签有name，尝试从tagsChinese中查找对应的中文
  if (tag.name && tag.name in tagsChinese) {
    return tagsChinese[tag.name as keyof typeof tagsChinese]
  }
  
  // 如果都没有，返回原始名称
  return tag.display_name || tag.name || tag
}

